home *** CD-ROM | disk | FTP | other *** search
/ Libris Britannia 4 / science library(b).zip / science library(b) / PROGRAMM / ASSEMBLE / 0572.ZIP / COMPRESS.C < prev    next >
C/C++ Source or Header  |  1987-02-11  |  40KB  |  1,450 lines

  1. /* 
  2.  * Compress - data compression program 
  3.  */
  4. #define    min(a,b)    ((a>b) ? b : a)
  5. /*
  6.  * machine variants which require cc -Dmachine:  pdp11, z8000, pcxt
  7.  */
  8.  
  9. /*
  10.  * Set USERMEM to the maximum amount of physical user memory available
  11.  * in bytes.  USERMEM is used to determine the maximum BITS that can be used
  12.  * for compression.
  13.  *
  14.  * SACREDMEM is the amount of physical memory saved for others; compress
  15.  * will hog the rest.
  16.  */
  17. #ifndef SACREDMEM
  18. #define SACREDMEM    0L
  19. #endif
  20.  
  21. #ifndef USERMEM
  22. # define USERMEM     450000L    /* default user memory */
  23. #endif
  24.  
  25. #ifdef interdata        /* (Perkin-Elmer) */
  26. #define SIGNED_COMPARE_SLOW    /* signed compare is slower than unsigned */
  27. #endif
  28.  
  29. #ifdef pdp11
  30. # define BITS     12    /* max bits/code for 16-bit machine */
  31. # define NO_UCHAR    /* also if "unsigned char" functions as signed char */
  32. # undef USERMEM 
  33. #endif /* pdp11 */    /* don't forget to compile with -i */
  34.  
  35. #ifdef z8000
  36. # define BITS     12
  37. # undef vax        /* weird preprocessor */
  38. # undef USERMEM 
  39. #endif /* z8000 */
  40.  
  41. #ifdef pcxt
  42. # define BITS   12
  43. # undef USERMEM
  44. #endif /* pcxt */
  45.  
  46. /*
  47.  * For the Microsoft C Compiler Version 4.0 use:
  48.  *   cl -Dmsc4 -Ox -F3000 compress.c \lib\ssetargv -o compress.e
  49.  *   exepack compress.e compress.exe
  50.  *   del compress.e
  51.  */
  52. #ifdef msc4
  53. # define DOS
  54. # define BITS    16
  55. # undef USERMEM
  56. #endif
  57.  
  58. #ifdef USERMEM
  59. # if USERMEM >= (433484L+SACREDMEM)
  60. #  define PBITS    16
  61. # else
  62. #  if USERMEM >= (229600+SACREDMEM)
  63. #   define PBITS    15
  64. #  else
  65. #   if USERMEM >= (127536+SACREDMEM)
  66. #    define PBITS    14
  67. #   else
  68. #    if USERMEM >= (73464+SACREDMEM)
  69. #     define PBITS    13
  70. #    else
  71. #     define PBITS    12
  72. #    endif
  73. #   endif
  74. #  endif
  75. # endif
  76. # undef USERMEM
  77. #endif /* USERMEM */
  78.  
  79. #ifdef PBITS        /* Preferred BITS for this memory size */
  80. # ifndef BITS
  81. #  define BITS PBITS
  82. # endif /* BITS */
  83. #endif /* PBITS */
  84.  
  85. #if BITS == 16
  86. # define HSIZE    69001L        /* 95% occupancy */
  87. #endif
  88. #if BITS == 15
  89. # define HSIZE    35023L        /* 94% occupancy */
  90. #endif
  91. #if BITS == 14
  92. # define HSIZE    18013        /* 91% occupancy */
  93. #endif
  94. #if BITS == 13
  95. # define HSIZE    9001        /* 91% occupancy */
  96. #endif
  97. #if BITS <= 12
  98. # define HSIZE    5003        /* 80% occupancy */
  99. #endif
  100.  
  101. /*
  102.  * a code_int must be able to hold 2**BITS values of type int, and also -1
  103.  */
  104. #if BITS > 15
  105. typedef long int    code_int;
  106. #else
  107. typedef int        code_int;
  108. #endif
  109.  
  110. #ifdef SIGNED_COMPARE_SLOW
  111. typedef unsigned long int count_int;
  112. typedef unsigned short int count_short;
  113. #else
  114. typedef long int      count_int;
  115. #endif
  116.  
  117. #ifdef NO_UCHAR
  118.  typedef char    char_type;
  119. #else
  120.  typedef    unsigned char    char_type;
  121. #endif /* UCHAR */
  122. char_type magic_header[] = { "\037\235" };    /* 1F 9D */
  123.  
  124. /* Defines for third byte of header */
  125. #define BIT_MASK    0x1f
  126. #define BLOCK_MASK    0x80
  127. /* Masks 0x40 and 0x20 are free.  I think 0x20 should mean that there is
  128.    a fourth header byte (for expansion).
  129. */
  130. #define INIT_BITS 9            /* initial number of bits/code */
  131.  
  132. /*
  133.  * compress.c - File compression ala IEEE Computer, June 1984.
  134.  *
  135.  * Authors:    Spencer W. Thomas    (decvax!harpo!utah-cs!utah-gr!thomas)
  136.  *        Jim McKie        (decvax!mcvax!jim)
  137.  *        Steve Davies        (decvax!vax135!petsd!peora!srd)
  138.  *        Ken Turkowski        (decvax!decwrl!turtlevax!ken)
  139.  *        James A. Woods        (decvax!ihnp4!ames!jaw)
  140.  *        Joe Orost        (decvax!vax135!petsd!joe)
  141.  *              Phil Suematsu        (ihnp4!decvax!ucla-an!conexch!phil)
  142.  *
  143.  * $Header: compress.c,v 4.1 87/02/11 21:03:27 phil Release $
  144.  * $Log:    compress.c,v $
  145.  *
  146.  * Revision 4.1  87/02/11  21:03:27  phil
  147.  * Added msc4 option for Microsoft C Compiler Version 4.0.  Added L's to
  148.  * several potentially long constants.
  149.  *
  150.  * Revision 4.0  85/07/30  12:50:00  joe
  151.  * Removed ferror() calls in output routine on every output except first.
  152.  * Prepared for release to the world.
  153.  * 
  154.  * Revision 3.6  85/07/04  01:22:21  joe
  155.  * Remove much wasted storage by overlaying hash table with the tables
  156.  * used by decompress: tab_suffix[1<<BITS], stack[8000].  Updated USERMEM
  157.  * computations.  Fixed dump_tab() DEBUG routine.
  158.  *
  159.  * Revision 3.5  85/06/30  20:47:21  jaw
  160.  * Change hash function to use exclusive-or.  Rip out hash cache.  These
  161.  * speedups render the megamemory version defunct, for now.  Make decoder
  162.  * stack global.  Parts of the RCS trunks 2.7, 2.6, and 2.1 no longer apply.
  163.  *
  164.  * Revision 3.4  85/06/27  12:00:00  ken
  165.  * Get rid of all floating-point calculations by doing all compression ratio
  166.  * calculations in fixed point.
  167.  *
  168.  * Revision 3.3  85/06/24  21:53:24  joe
  169.  * Incorporate portability suggestion for M_XENIX.  Got rid of text on #else
  170.  * and #endif lines.  Cleaned up #ifdefs for vax and interdata.
  171.  *
  172.  * Revision 3.2  85/06/06  21:53:24  jaw
  173.  * Incorporate portability suggestions for Z8000, IBM PC/XT from mailing list.
  174.  * Default to "quiet" output (no compression statistics).
  175.  *
  176.  * Revision 3.1  85/05/12  18:56:13  jaw
  177.  * Integrate decompress() stack speedups (from early pointer mods by McKie).
  178.  * Repair multi-file USERMEM gaffe.  Unify 'force' flags to mimic semantics
  179.  * of SVR2 'pack'.  Streamline block-compress table clear logic.  Increase 
  180.  * output byte count by magic number size.
  181.  * 
  182.  * Revision 3.0   84/11/27  11:50:00  petsd!joe
  183.  * Set HSIZE depending on BITS.  Set BITS depending on USERMEM.  Unrolled
  184.  * loops in clear routines.  Added "-C" flag for 2.0 compatibility.  Used
  185.  * unsigned compares on Perkin-Elmer.  Fixed foreground check.
  186.  *
  187.  * Revision 2.7   84/11/16  19:35:39  ames!jaw
  188.  * Cache common hash codes based on input statistics; this improves
  189.  * performance for low-density raster images.  Pass on #ifdef bundle
  190.  * from Turkowski.
  191.  *
  192.  * Revision 2.6   84/11/05  19:18:21  ames!jaw
  193.  * Vary size of hash tables to reduce time for small files.
  194.  * Tune PDP-11 hash function.
  195.  *
  196.  * Revision 2.5   84/10/30  20:15:14  ames!jaw
  197.  * Junk chaining; replace with the simpler (and, on the VAX, faster)
  198.  * double hashing, discussed within.  Make block compression standard.
  199.  *
  200.  * Revision 2.4   84/10/16  11:11:11  ames!jaw
  201.  * Introduce adaptive reset for block compression, to boost the rate
  202.  * another several percent.  (See mailing list notes.)
  203.  *
  204.  * Revision 2.3   84/09/22  22:00:00  petsd!joe
  205.  * Implemented "-B" block compress.  Implemented REVERSE sorting of tab_next.
  206.  * Bug fix for last bits.  Changed fwrite to putchar loop everywhere.
  207.  *
  208.  * Revision 2.2   84/09/18  14:12:21  ames!jaw
  209.  * Fold in news changes, small machine typedef from thomas,
  210.  * #ifdef interdata from joe.
  211.  *
  212.  * Revision 2.1   84/09/10  12:34:56  ames!jaw
  213.  * Configured fast table lookup for 32-bit machines.
  214.  * This cuts user time in half for b <= FBITS, and is useful for news batching
  215.  * from VAX to PDP sites.  Also sped up decompress() [fwrite->putc] and
  216.  * added signal catcher [plus beef in writeerr()] to delete effluvia.
  217.  *
  218.  * Revision 2.0   84/08/28  22:00:00  petsd!joe
  219.  * Add check for foreground before prompting user.  Insert maxbits into
  220.  * compressed file.  Force file being uncompressed to end with ".Z".
  221.  * Added "-c" flag and "zcat".  Prepared for release.
  222.  *
  223.  * Revision 1.10  84/08/24  18:28:00  turtlevax!ken
  224.  * Will only compress regular files (no directories), added a magic number
  225.  * header (plus an undocumented -n flag to handle old files without headers),
  226.  * added -f flag to force overwriting of possibly existing destination file,
  227.  * otherwise the user is prompted for a response.  Will tack on a .Z to a
  228.  * filename if it doesn't have one when decompressing.  Will only replace
  229.  * file if it was compressed.
  230.  *
  231.  * Revision 1.9  84/08/16  17:28:00  turtlevax!ken
  232.  * Removed scanargs(), getopt(), added .Z extension and unlimited number of
  233.  * filenames to compress.  Flags may be clustered (-Ddvb12) or separated
  234.  * (-D -d -v -b 12), or combination thereof.  Modes and other status is
  235.  * copied with copystat().  -O bug for 4.2 seems to have disappeared with
  236.  * 1.8.
  237.  *
  238.  * Revision 1.8  84/08/09  23:15:00  joe
  239.  * Made it compatible with vax version, installed jim's fixes/enhancements
  240.  *
  241.  * Revision 1.6  84/08/01  22:08:00  joe
  242.  * Sped up algorithm significantly by sorting the compress chain.
  243.  *
  244.  * Revision 1.5  84/07/13  13:11:00  srd
  245.  * Added C version of vax asm routines.  Changed structure to arrays to
  246.  * save much memory.  Do unsigned compares where possible (faster on
  247.  * Perkin-Elmer)
  248.  *
  249.  * Revision 1.4  84/07/05  03:11:11  thomas
  250.  * Clean up the code a little and lint it.  (Lint complains about all
  251.  * the regs used in the asm, but I'm not going to "fix" this.)
  252.  *
  253.  * Revision 1.3  84/07/05  02:06:54  thomas
  254.  * Minor fixes.
  255.  *
  256.  * Revision 1.2  84/07/05  00:27:27  thomas
  257.  * Add variable bit length output.
  258.  *
  259.  */
  260. static char rcs_ident[] = "$Header: compress.c,v 4.1 87/02/11 21:03:27 phil Release $";
  261.  
  262. #include <stdio.h>
  263. #include <ctype.h>
  264. #include <signal.h>
  265. #include <sys/types.h>
  266. #include <sys/stat.h>
  267.  
  268. #define ARGVAL() (*++(*argv) || (--argc && *++argv))
  269.  
  270. int n_bits;                /* number of bits/code */
  271. int maxbits = BITS;            /* user settable max # bits/code */
  272. code_int maxcode;            /* maximum code, given n_bits */
  273. code_int maxmaxcode;            /* should NEVER generate this code */
  274. #ifdef COMPATIBLE        /* But wrong! */
  275. # define MAXCODE(n_bits)    ((code_int)1L << (n_bits) - 1)
  276. #else
  277. # define MAXCODE(n_bits)    (((code_int)1L << (n_bits)) - 1)
  278. #endif /* COMPATIBLE */
  279.  
  280. count_int huge htab [HSIZE];
  281. unsigned short huge codetab [HSIZE];
  282. #define htabof(i)    htab[i]
  283. #define codetabof(i)    codetab[i]
  284. code_int hsize = HSIZE;            /* for dynamic table sizing */
  285. count_int fsize;
  286.  
  287. /*
  288.  * To save much memory, we overlay the table used by compress() with those
  289.  * used by decompress().  The tab_prefix table is the same size and type
  290.  * as the codetab.  The tab_suffix table needs 2**BITS characters.  We
  291.  * get this from the beginning of htab.  The output stack uses the rest
  292.  * of htab, and contains characters.  There is plenty of room for any
  293.  * possible stack (stack used to be 8000 characters).
  294.  */
  295.  
  296. #define tab_prefixof(i)    codetabof(i)
  297. # define tab_suffixof(i)    ((char_type huge *)(htab))[i]
  298. # define de_stack        ((char_type huge *)&tab_suffixof(1L<<BITS))
  299.  
  300. code_int free_ent = 0;            /* first unused entry */
  301. int exit_stat = 0;
  302.  
  303. code_int getcode();
  304.  
  305. Usage() {
  306. #ifdef DEBUG
  307. fprintf(stderr,"Usage: compress [-dDVfc] [-b maxbits] [file ...]\n");
  308. }
  309. int debug = 0;
  310. #else
  311. fprintf(stderr,"Usage: compress [-dfvcV] [-b maxbits] [file ...]\n");
  312. }
  313. #endif /* DEBUG */
  314. int nomagic = 0;    /* Use a 3-byte magic number header, unless old file */
  315. int zcat_flg = 0;    /* Write output on stdout, suppress messages */
  316. int quiet = 1;        /* don't tell me about compression */
  317.  
  318. /*
  319.  * block compression parameters -- after all codes are used up,
  320.  * and compression rate changes, start over.
  321.  */
  322. int block_compress = BLOCK_MASK;
  323. int clear_flg = 0;
  324. long int ratio = 0;
  325. #define CHECK_GAP 10000    /* ratio check interval */
  326. count_int checkpoint = CHECK_GAP;
  327. /*
  328.  * the next two codes should not be changed lightly, as they must not
  329.  * lie within the contiguous general code space.
  330.  */ 
  331. #define FIRST    257    /* first free entry */
  332. #define    CLEAR    256    /* table clear output code */
  333.  
  334. int force = 0;
  335. char ofname [100];
  336. #ifdef DEBUG
  337. int verbose = 0;
  338. #endif /* DEBUG */
  339. int (*bgnd_flag)();
  340.  
  341. int do_decomp = 0;
  342.  
  343. /*****************************************************************
  344.  * TAG( main )
  345.  *
  346.  * Algorithm from "A Technique for High Performance Data Compression",
  347.  * Terry A. Welch, IEEE Computer Vol 17, No 6 (June 1984), pp 8-19.
  348.  *
  349.  * Usage: compress [-dfvc] [-b bits] [file ...]
  350.  * Inputs:
  351.  *    -d:        If given, decompression is done instead.
  352.  *
  353.  *      -c:         Write output on stdout, don't remove original.
  354.  *
  355.  *      -b:         Parameter limits the max number of bits/code.
  356.  *
  357.  *    -f:        Forces output file to be generated, even if one already
  358.  *            exists, and even if no space is saved by compressing.
  359.  *            If -f is not used, the user will be prompted if stdin is
  360.  *            a tty, otherwise, the output file will not be overwritten.
  361.  *
  362.  *      -v:        Write compression statistics
  363.  *
  364.  *     file ...:   Files to be compressed.  If none specified, stdin
  365.  *            is used.
  366.  * Outputs:
  367.  *    file.Z:        Compressed form of file with same mode, owner, and utimes
  368.  *     or stdout   (if stdin used as input)
  369.  *
  370.  * Assumptions:
  371.  *    When filenames are given, replaces with the compressed version
  372.  *    (.Z suffix) only if the file decreases in size.
  373.  * Algorithm:
  374.  *     Modified Lempel-Ziv method (LZW).  Basically finds common
  375.  * substrings and replaces them with a variable size code.  This is
  376.  * deterministic, and can be done on the fly.  Thus, the decompression
  377.  * procedure needs no input table, but tracks the way the table was built.
  378.  */
  379.  
  380. main( argc, argv )
  381. register int argc; char **argv;
  382. {
  383.     int overwrite = 0;    /* Do not overwrite unless given -f flag */
  384.     char tempname[100];
  385.     char **filelist, **fileptr;
  386.     char *cp, *rindex(), *malloc();
  387.     struct stat statbuf;
  388.     extern onintr(), oops();
  389.  
  390.  
  391.     if ( (bgnd_flag = signal ( SIGINT, SIG_IGN )) != SIG_IGN ) {
  392.     signal ( SIGINT, onintr );
  393. #ifndef DOS
  394.     signal ( SIGSEGV, oops );
  395. #endif
  396.     }
  397.  
  398. #ifdef COMPATIBLE
  399.     nomagic = 1;    /* Original didn't have a magic number */
  400. #endif /* COMPATIBLE */
  401.  
  402.     filelist = fileptr = (char **)(malloc(argc * sizeof(*argv)));
  403.     *filelist = NULL;
  404.  
  405.     if((cp = rindex(argv[0], '/')) != 0) {
  406.     cp++;
  407.     } else {
  408.     cp = argv[0];
  409.     }
  410.     if(strcmp(cp, "uncompress") == 0) {
  411.     do_decomp = 1;
  412.     } else if(strcmp(cp, "zcat") == 0) {
  413.     do_decomp = 1;
  414.     zcat_flg = 1;
  415.     }
  416.  
  417. #ifdef BSD4_2
  418.     /* 4.2BSD dependent - take it out if not */
  419.     setlinebuf( stderr );
  420. #endif /* BSD4_2 */
  421.  
  422.     /* Argument Processing
  423.      * All flags are optional.
  424.      * -D => debug
  425.      * -V => print Version; debug verbose
  426.      * -d => do_decomp
  427.      * -v => unquiet
  428.      * -f => force overwrite of output file
  429.      * -n => no header: useful to uncompress old files
  430.      * -b maxbits => maxbits.  If -b is specified, then maxbits MUST be
  431.      *        given also.
  432.      * -c => cat all output to stdout
  433.      * -C => generate output compatible with compress 2.0.
  434.      * if a string is left, must be an input filename.
  435.      */
  436.     for (argc--, argv++; argc > 0; argc--, argv++) {
  437.     if (**argv == '-') {    /* A flag argument */
  438.         while (*++(*argv)) {    /* Process all flags in this arg */
  439.         switch (**argv) {
  440. #ifdef DEBUG
  441.             case 'D':
  442.             debug = 1;
  443.             break;
  444.             case 'V':
  445.             verbose = 1;
  446.             version();
  447.             break;
  448. #else
  449.             case 'V':
  450.             version();
  451.             break;
  452. #endif /* DEBUG */
  453.             case 'v':
  454.             quiet = 0;
  455.             break;
  456.             case 'd':
  457.             do_decomp = 1;
  458.             break;
  459.             case 'f':
  460.             case 'F':
  461.             overwrite = 1;
  462.             force = 1;
  463.             break;
  464.             case 'n':
  465.             nomagic = 1;
  466.             break;
  467.             case 'C':
  468.             block_compress = 0;
  469.             break;
  470.             case 'b':
  471.             if (!ARGVAL()) {
  472.                 fprintf(stderr, "Missing maxbits\n");
  473.                 Usage();
  474.                 exit(1);
  475.             }
  476.             maxbits = atoi(*argv);
  477.             goto nextarg;
  478.             case 'c':
  479.             zcat_flg = 1;
  480.             break;
  481.             case 'q':
  482.             quiet = 1;
  483.             break;
  484.             default:
  485.             fprintf(stderr, "Unknown flag: '%c'; ", **argv);
  486.             Usage();
  487.             exit(1);
  488.         }
  489.         }
  490.     }
  491.     else {        /* Input file name */
  492.         *fileptr++ = *argv;    /* Build input file list */
  493.         *fileptr = NULL;
  494.         /* process nextarg; */
  495.     }
  496.     nextarg: continue;
  497.     }
  498.  
  499.     if(maxbits < INIT_BITS) maxbits = INIT_BITS;
  500.     if (maxbits > BITS) maxbits = BITS;
  501.     maxmaxcode = (code_int)1L << maxbits;
  502.  
  503.     if (*filelist != NULL) {
  504.     for (fileptr = filelist; *fileptr; fileptr++) {
  505.         exit_stat = 0;
  506.         if (do_decomp != 0) {            /* DECOMPRESSION */
  507.         /* Check for .Z suffix */
  508.         if (strcmp(*fileptr + strlen(*fileptr) - 2, ".Z") != 0) {
  509.             /* No .Z: tack one on */
  510.             strcpy(tempname, *fileptr);
  511.             strcat(tempname, ".Z");
  512.             *fileptr = tempname;
  513.         }
  514.         /* Open input file */
  515. #ifndef msc4
  516.         if ((freopen(*fileptr, "r", stdin)) == NULL) {
  517. #else
  518.         if ((freopen(*fileptr, "rb", stdin)) == NULL) {
  519. #endif
  520.             perror(*fileptr); continue;
  521.         }
  522.         /* Check the magic number */
  523.         if (nomagic == 0) {
  524.             if ((getchar() != (magic_header[0] & 0xFF))
  525.              || (getchar() != (magic_header[1] & 0xFF))) {
  526.             fprintf(stderr, "%s: not in compressed format\n",
  527.                 *fileptr);
  528.             continue;
  529.             }
  530.             maxbits = getchar();    /* set -b from file */
  531.             block_compress = maxbits & BLOCK_MASK;
  532.             maxbits &= BIT_MASK;
  533.             maxmaxcode = (code_int)1L << maxbits;
  534.             if(maxbits > BITS) {
  535.             fprintf(stderr,
  536.             "%s: compressed with %d bits, can only handle %d bits\n",
  537.             *fileptr, maxbits, BITS);
  538.             continue;
  539.             }
  540.         }
  541.         /* Generate output filename */
  542.         strcpy(ofname, *fileptr);
  543.         ofname[strlen(*fileptr) - 2] = '\0';  /* Strip off .Z */
  544.         } else {                    /* COMPRESSION */
  545.         if (strcmp(*fileptr + strlen(*fileptr) - 2, ".Z") == 0) {
  546.                 fprintf(stderr, "%s: already has .Z suffix -- no change\n",
  547.                 *fileptr);
  548.             continue;
  549.         }
  550.         /* Open input file */
  551. #ifndef msc4
  552.         if ((freopen(*fileptr, "r", stdin)) == NULL) {
  553. #else
  554.         if ((freopen(*fileptr, "rb", stdin)) == NULL) {
  555. #endif
  556.             perror(*fileptr); continue;
  557.         }
  558.         stat ( *fileptr, &statbuf );
  559.         fsize = (long) statbuf.st_size;
  560.         /*
  561.          * tune hash table size for small files -- ad hoc,
  562.          * but the sizes match earlier #defines, which
  563.          * serve as upper bounds on the number of output codes. 
  564.          */
  565.         hsize = HSIZE;
  566.         if ( fsize < (1 << 12) )
  567.             hsize = min ( 5003, HSIZE );
  568.         else if ( fsize < (1 << 13) )
  569.             hsize = min ( 9001, HSIZE );
  570.         else if ( fsize < (1 << 14) )
  571.             hsize = min ( 18013, HSIZE );
  572.         else if ( fsize < (1 << 15) )
  573.             hsize = min ( 35023, HSIZE );
  574.         else if ( fsize < 47000 )
  575.             hsize = min ( 50021, HSIZE );
  576.  
  577.         /* Generate output filename */
  578.         strcpy(ofname, *fileptr);
  579. #ifndef BSD4_2        /* Short filenames */
  580.         if ((cp=rindex(ofname,'/')) != NULL)    cp++;
  581.         else                    cp = ofname;
  582.         if (strlen(cp) > 12) {
  583.             fprintf(stderr,"%s: filename too long to tack on .Z\n",cp);
  584.             continue;
  585.         }
  586. #endif  /* BSD4_2        Long filenames allowed */
  587.         strcat(ofname, ".Z");
  588.         }
  589.         /* Check for overwrite of existing file */
  590.         if (overwrite == 0 && zcat_flg == 0) {
  591.         if (stat(ofname, &statbuf) == 0) {
  592.             char response[2];
  593.             response[0] = 'n';
  594.             fprintf(stderr, "%s already exists;", ofname);
  595.             if (foreground()) {
  596.             fprintf(stderr, " do you wish to overwrite %s (y or n)? ",
  597.             ofname);
  598.             fflush(stderr);
  599.             read(2, response, 2);
  600.             while (response[1] != '\n') {
  601.                 if (read(2, response+1, 1) < 0) {    /* Ack! */
  602.                 perror("stderr"); break;
  603.                 }
  604.             }
  605.             }
  606.             if (response[0] != 'y') {
  607.             fprintf(stderr, "\tnot overwritten\n");
  608.             continue;
  609.             }
  610.         }
  611.         }
  612.         if(zcat_flg == 0) {        /* Open output file */
  613. #ifndef msc4
  614.         if (freopen(ofname, "w", stdout) == NULL) {
  615. #else
  616.         if (freopen(ofname, "wb", stdout) == NULL) {
  617. #endif
  618.             perror(ofname);
  619.             continue;
  620.         }
  621.         if(!quiet)
  622.             fprintf(stderr, "%s: ", *fileptr);
  623.         }
  624.  
  625.         /* Actually do the compression/decompression */
  626.         if (do_decomp == 0)    compress();
  627. #ifndef DEBUG
  628.         else            decompress();
  629. #else
  630.         else if (debug == 0)    decompress();
  631.         else            printcodes();
  632.         if (verbose)        dump_tab();
  633. #endif /* DEBUG */
  634.         if(zcat_flg == 0) {
  635.         copystat(*fileptr, ofname);    /* Copy stats */
  636.         if((exit_stat == 1) || (!quiet))
  637.             putc('\n', stderr);
  638.         }
  639.     }
  640.     } else {        /* Standard input */
  641.     if (do_decomp == 0) {
  642.         compress();
  643. #ifdef DEBUG
  644.         if(verbose)        dump_tab();
  645. #endif /* DEBUG */
  646.         if(!quiet)
  647.             putc('\n', stderr);
  648.     } else {
  649.         /* Check the magic number */
  650.         if (nomagic == 0) {
  651.         if ((getchar()!=(magic_header[0] & 0xFF))
  652.          || (getchar()!=(magic_header[1] & 0xFF))) {
  653.             fprintf(stderr, "stdin: not in compressed format\n");
  654.             exit(1);
  655.         }
  656.         maxbits = getchar();    /* set -b from file */
  657.         block_compress = maxbits & BLOCK_MASK;
  658.         maxbits &= BIT_MASK;
  659.         maxmaxcode = (code_int)1L << maxbits;
  660.         fsize = 100000;        /* assume stdin large for USERMEM */
  661.         if(maxbits > BITS) {
  662.             fprintf(stderr,
  663.             "stdin: compressed with %d bits, can only handle %d bits\n",
  664.             maxbits, BITS);
  665.             exit(1);
  666.         }
  667.         }
  668. #ifndef DEBUG
  669.         decompress();
  670. #else
  671.         if (debug == 0)    decompress();
  672.         else        printcodes();
  673.         if (verbose)    dump_tab();
  674. #endif /* DEBUG */
  675.     }
  676.     }
  677.     exit(exit_stat);
  678. }
  679.  
  680. static int offset;
  681. long int in_count = 1;            /* length of input */
  682. long int bytes_out;            /* length of compressed output */
  683. long int out_count = 0;            /* # of codes output (for debugging) */
  684.  
  685. /*
  686.  * compress stdin to stdout
  687.  *
  688.  * Algorithm:  use open addressing double hashing (no chaining) on the 
  689.  * prefix code / next character combination.  We do a variant of Knuth's
  690.  * algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
  691.  * secondary probe.  Here, the modular division first probe is gives way
  692.  * to a faster exclusive-or manipulation.  Also do block compression with
  693.  * an adaptive reset, whereby the code table is cleared when the compression
  694.  * ratio decreases, but after the table fills.  The variable-length output
  695.  * codes are re-sized at this point, and a special CLEAR code is generated
  696.  * for the decompressor.  Late addition:  construct the table according to
  697.  * file size for noticeable speed improvement on small files.  Please direct
  698.  * questions about this implementation to ames!jaw.
  699.  */
  700.  
  701. compress() {
  702.     register long fcode;
  703.     register code_int i = 0;    /* must hold HSIZE */
  704.     register int c;
  705.     register unsigned ent;    /* must hold BITS bits */
  706.     register code_int disp;    /* must hold HSIZE */
  707.     register code_int hsize_reg;
  708.     register int hshift;
  709.  
  710. #ifndef COMPATIBLE
  711.     if (nomagic == 0) {
  712.     putchar(magic_header[0]); putchar(magic_header[1]);
  713.     putchar((char)(maxbits | block_compress));
  714.     if(ferror(stdout))
  715.         writeerr();
  716.     }
  717. #endif /* COMPATIBLE */
  718.  
  719.     offset = 0;
  720.     bytes_out = 3;        /* includes 3-byte header mojo */
  721.     out_count = 0;
  722.     clear_flg = 0;
  723.     ratio = 0;
  724.     in_count = 1;
  725.     checkpoint = CHECK_GAP;
  726.     maxcode = MAXCODE(n_bits = INIT_BITS);
  727.     free_ent = ((block_compress) ? FIRST : 256 );
  728.  
  729.     ent = getchar ();
  730.  
  731.     hshift = 0;
  732.     for ( fcode = (long) hsize;  fcode < 65536L; fcode *= 2L )
  733.         hshift++;
  734.     hshift = 8 - hshift;        /* set hash code range bound */
  735.  
  736.     hsize_reg = hsize;
  737.     cl_hash( (count_int) hsize_reg);        /* clear hash table */
  738.  
  739. #ifdef SIGNED_COMPARE_SLOW
  740.     while ( (c = getchar()) != (unsigned) EOF ) {
  741. #else
  742.     while ( (c = getchar()) != EOF ) {
  743. #endif
  744.     in_count++;
  745.     fcode = (long) (((long) c << maxbits) + ent);
  746.      i = ((c << hshift) ^ ent);    /* xor hashing */
  747.  
  748.     if ( htabof (i) == fcode ) {
  749.         ent = codetabof (i);
  750.         continue;
  751.     } else if ( (long)htabof (i) < 0 )    /* empty slot */
  752.         goto nomatch;
  753.      disp = hsize_reg - i;        /* secondary hash (after G. Knott) */
  754.     if ( i == 0 )
  755.         disp = 1;
  756. probe:
  757.     if ( (i -= disp) < 0 )
  758.         i += hsize_reg;
  759.  
  760.     if ( htabof (i) == fcode ) {
  761.         ent = codetabof (i);
  762.         continue;
  763.     }
  764.     if ( (long)htabof (i) > 0 ) 
  765.         goto probe;
  766. nomatch:
  767.     output ( (code_int) ent );
  768.     out_count++;
  769.      ent = c;
  770. #ifdef SIGNED_COMPARE_SLOW
  771.     if ( (unsigned) free_ent < (unsigned) maxmaxcode) {
  772. #else
  773.     if ( free_ent < maxmaxcode ) {
  774. #endif
  775.          codetabof (i) = free_ent++;    /* code -> hashtable */
  776.         htabof (i) = fcode;
  777.     }
  778.     else if ( (count_int)in_count >= checkpoint && block_compress )
  779.         cl_block ();
  780.     }
  781.     /*
  782.      * Put out the final code.
  783.      */
  784.     output( (code_int)ent );
  785.     out_count++;
  786.     output( (code_int)-1 );
  787.  
  788.     /*
  789.      * Print out stats on stderr
  790.      */
  791.     if(zcat_flg == 0 && !quiet) {
  792. #ifdef DEBUG
  793.     fprintf( stderr,
  794.         "%ld chars in, %ld codes (%ld bytes) out, compression factor: ",
  795.         in_count, out_count, bytes_out );
  796.     prratio( stderr, in_count, bytes_out );
  797.     fprintf( stderr, "\n");
  798.     fprintf( stderr, "\tCompression as in compact: " );
  799.     prratio( stderr, in_count-bytes_out, in_count );
  800.     fprintf( stderr, "\n");
  801.     fprintf( stderr, "\tLargest code (of last block) was %d (%d bits)\n",
  802.         free_ent - 1, n_bits );
  803. #else /* !DEBUG */
  804.     fprintf( stderr, "Compression: " );
  805.     prratio( stderr, in_count-bytes_out, in_count );
  806. #endif /* DEBUG */
  807.     }
  808.     if(bytes_out > in_count)    /* exit(2) if no savings */
  809.     exit_stat = 2;
  810.     return;
  811. }
  812.  
  813. /*****************************************************************
  814.  * TAG( output )
  815.  *
  816.  * Output the given code.
  817.  * Inputs:
  818.  *     code:    A n_bits-bit integer.  If == -1, then EOF.  This assumes
  819.  *        that n_bits =< (long)wordsize - 1.
  820.  * Outputs:
  821.  *     Outputs code to the file.
  822.  * Assumptions:
  823.  *    Chars are 8 bits long.
  824.  * Algorithm:
  825.  *     Maintain a BITS character long buffer (so that 8 codes will
  826.  * fit in it exactly).  Use the VAX insv instruction to insert each
  827.  * code in turn.  When the buffer fills up empty it and start over.
  828.  */
  829.  
  830. static char buf[BITS];
  831.  
  832. #ifndef vax
  833. char_type lmask[9] = {0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80, 0x00};
  834. char_type rmask[9] = {0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff};
  835. #endif /* vax */
  836.  
  837. output( incode )
  838.   code_int  incode;
  839. {
  840. #ifdef DEBUG
  841.     static int col = 0;
  842. #endif /* DEBUG */
  843.  
  844.     /*
  845.      * On the VAX, it is important to have the register declarations
  846.      * in exactly the order given, or the asm will break.
  847.      */
  848.     register int r_off = offset, bits= n_bits;
  849.     register unsigned short code;
  850.     register char * bp = buf;
  851.  
  852. #ifdef DEBUG
  853.     if ( verbose )
  854.         fprintf( stderr, "%5d%c", code,
  855.             (col+=6) >= 74 ? (col = 0, '\n') : ' ' );
  856. #endif /* DEBUG */
  857.     if ( incode >= 0 ) {
  858.     code = incode;
  859. #ifdef vax
  860.     /* VAX DEPENDENT!! Implementation on other machines is below.
  861.      *
  862.      * Translation: Insert BITS bits from the argument starting at
  863.      * offset bits from the beginning of buf.
  864.      */
  865.     0;    /* Work around for pcc -O bug with asm and if stmt */
  866.     asm( "insv    4(ap),r11,r10,(r9)" );
  867. #else /* not a vax */
  868. /* 
  869.  * byte/bit numbering on the VAX is simulated by the following code
  870.  */
  871.     /*
  872.      * Get to the first byte.
  873.      */
  874.     bp += (r_off >> 3);
  875.     r_off &= 7;
  876.     /*
  877.      * Since code is always >= 8 bits, only need to mask the first
  878.      * hunk on the left.
  879.      */
  880.     *bp = (*bp & rmask[r_off]) | (code << r_off) & lmask[r_off];
  881.     bp++;
  882.     bits -= (8 - r_off);
  883.     code >>= 8 - r_off;
  884.     /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
  885.     if ( bits >= 8 ) {
  886.         *bp++ = code;
  887.         code >>= 8;
  888.         bits -= 8;
  889.     }
  890.     /* Last bits. */
  891.     if (bits)
  892.         *bp = code;
  893. #endif /* vax */
  894.     offset += n_bits;
  895.     if ( offset == (n_bits << 3) ) {
  896.         bp = buf;
  897.         bits = n_bits;
  898.         bytes_out += bits;
  899.         do
  900.         putchar(*bp++);
  901.         while(--bits);
  902.         offset = 0;
  903.     }
  904.  
  905.     /*
  906.      * If the next entry is going to be too big for the code size,
  907.      * then increase it, if possible.
  908.      */
  909.     if ( free_ent > maxcode || (clear_flg > 0))
  910.     {
  911.         /*
  912.          * Write the whole buffer, because the input side won't
  913.          * discover the size increase until after it has read it.
  914.          */
  915.         if ( offset > 0 ) {
  916.         if( fwrite( buf, 1, n_bits, stdout ) != n_bits)
  917.             writeerr();
  918.         bytes_out += n_bits;
  919.         }
  920.         offset = 0;
  921.  
  922.         if ( clear_flg ) {
  923.                 maxcode = MAXCODE (n_bits = INIT_BITS);
  924.             clear_flg = 0;
  925.         }
  926.         else {
  927.             n_bits++;
  928.             if ( n_bits == maxbits )
  929.             maxcode = maxmaxcode;
  930.             else
  931.             maxcode = MAXCODE(n_bits);
  932.         }
  933. #ifdef DEBUG
  934.         if ( debug ) {
  935.         fprintf( stderr, "\nChange to %d bits\n", n_bits );
  936.         col = 0;
  937.         }
  938. #endif /* DEBUG */
  939.     }
  940.     } else {
  941.     /*
  942.      * At EOF, write the rest of the buffer.
  943.      */
  944.     if ( offset > 0 )
  945.         fwrite( buf, 1, (offset + 7) / 8, stdout );
  946.     bytes_out += (offset + 7) / 8;
  947.     offset = 0;
  948.     fflush( stdout );
  949. #ifdef DEBUG
  950.     if ( verbose )
  951.         fprintf( stderr, "\n" );
  952. #endif /* DEBUG */
  953.     if( ferror( stdout ) )
  954.         writeerr();
  955.     }
  956. }
  957.  
  958. /*
  959.  * Decompress stdin to stdout.  This routine adapts to the codes in the
  960.  * file building the "string" table on-the-fly; requiring no table to
  961.  * be stored in the compressed file.  The tables used herein are shared
  962.  * with those of the compress() routine.  See the definitions above.
  963.  */
  964.  
  965. decompress() {
  966.     register char_type huge *stackp;
  967.     register int finchar;
  968.     register unsigned short code;
  969.     register code_int oldcode, incode;
  970.  
  971.     /*
  972.      * As above, initialize the first 256 entries in the table.
  973.      */
  974.     maxcode = MAXCODE(n_bits = INIT_BITS);
  975.     for ( incode = 255; incode >= 0; incode-- ) {
  976.     tab_prefixof(incode) = 0;
  977.     tab_suffixof(incode) = (char_type)incode;
  978.     }
  979.     free_ent = ((block_compress) ? FIRST : 256 );
  980.  
  981.     finchar = oldcode = getcode();
  982.     if(oldcode == -1)    /* EOF already? */
  983.     return;            /* Get out of here */
  984.     putchar( finchar );        /* first code must be 8 bits = char */
  985.     if(ferror(stdout))        /* Crash if can't write */
  986.     writeerr();
  987.     stackp = de_stack;
  988.  
  989.     while ( (incode = getcode()) > -1 ) {
  990.  
  991.     code = incode;
  992.     if ( (code == CLEAR) && block_compress ) {
  993.         for ( incode = 255; incode >= 0; incode-- )
  994.         tab_prefixof(incode) = 0;
  995.         clear_flg = 1;
  996.         free_ent = FIRST - 1;
  997.         if ( (incode = getcode ()) == -1 )    /* O, untimely death! */
  998.         break;
  999.         code = incode;
  1000.     }
  1001.     /*
  1002.      * Special case for KwKwK string.
  1003.      */
  1004.     if ( code >= free_ent ) {
  1005.             *stackp++ = finchar;
  1006.         code = oldcode;
  1007.     }
  1008.  
  1009.     /*
  1010.      * Generate output characters in reverse order
  1011.      */
  1012.     while ( code >= 256 ) {        /* already unsigned compare */
  1013.         *stackp++ = tab_suffixof(code);
  1014.         code = tab_prefixof(code);
  1015.     }
  1016.     *stackp++ = finchar = tab_suffixof(code);
  1017.  
  1018.     /*
  1019.      * And put them out in forward order
  1020.      */
  1021.     do
  1022.         putchar ( *--stackp );
  1023.     while ( stackp > de_stack );
  1024.  
  1025.     /*
  1026.      * Generate the new entry.
  1027.      */
  1028.     if ( free_ent < maxmaxcode ) {
  1029.         code = free_ent++;
  1030.         tab_prefixof(code) = (unsigned short)oldcode;
  1031.         tab_suffixof(code) = finchar;
  1032.     } 
  1033.     /*
  1034.      * Remember previous code.
  1035.      */
  1036.     oldcode = incode;
  1037.     }
  1038.     fflush( stdout );
  1039.     if(ferror(stdout))
  1040.     writeerr();
  1041. }
  1042.  
  1043. /*****************************************************************
  1044.  * TAG( getcode )
  1045.  *
  1046.  * Read one code from the standard input.  If EOF, return -1.
  1047.  * Inputs:
  1048.  *     stdin
  1049.  * Outputs:
  1050.  *     code or -1 is returned.
  1051.  */
  1052.  
  1053. code_int getcode() {
  1054.     /*
  1055.      * On the VAX, it is important to have the register declarations
  1056.      * in exactly the order given, or the asm will break.
  1057.      */
  1058.     register unsigned short code;
  1059.     static int offset = 0, size = 0;
  1060.     static char_type buf[BITS];
  1061.     register int r_off, bits;
  1062.     register char_type *bp = buf;
  1063.  
  1064.     if ( clear_flg > 0 || offset >= size || free_ent > maxcode ) {
  1065.     /*
  1066.      * If the next entry will be too big for the current code
  1067.      * size, then we must increase the size.  This implies reading
  1068.      * a new buffer full, too.
  1069.      */
  1070.     if ( free_ent > maxcode ) {
  1071.         n_bits++;
  1072.         if ( n_bits == maxbits )
  1073.         maxcode = maxmaxcode;    /* won't get any bigger now */
  1074.         else
  1075.         maxcode = MAXCODE(n_bits);
  1076.     }
  1077.     if ( clear_flg > 0) {
  1078.             maxcode = MAXCODE (n_bits = INIT_BITS);
  1079.         clear_flg = 0;
  1080.     }
  1081.     size = fread( buf, 1, n_bits, stdin );
  1082.     if ( size <= 0 )
  1083.         return -1;            /* end of file */
  1084.     offset = 0;
  1085.     /* Round size down to integral number of codes */
  1086.     size = (size << 3) - (n_bits - 1);
  1087.     }
  1088.     r_off = offset;
  1089.     bits = n_bits;
  1090. #ifdef vax
  1091.     asm( "extzv   r10,r9,(r8),r11" );
  1092. #else /* not a vax */
  1093.     /*
  1094.      * Get to the first byte.
  1095.      */
  1096.     bp += (r_off >> 3);
  1097.     r_off &= 7;
  1098.     /* Get first part (low order bits) */
  1099. #ifdef NO_UCHAR
  1100.     code = ((*bp++ >> r_off) & rmask[8 - r_off]) & 0xff;
  1101. #else
  1102.     code = (*bp++ >> r_off);
  1103. #endif /* NO_UCHAR */
  1104.     bits -= (8 - r_off);
  1105.     r_off = 8 - r_off;        /* now, offset into code word */
  1106.     /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
  1107.     if ( bits >= 8 ) {
  1108. #ifdef NO_UCHAR
  1109.         code |= (*bp++ & 0xff) << r_off;
  1110. #else
  1111.         code |= *bp++ << r_off;
  1112. #endif /* NO_UCHAR */
  1113.         r_off += 8;
  1114.         bits -= 8;
  1115.     }
  1116.     /* high order bits. */
  1117.     code |= (*bp & rmask[bits]) << r_off;
  1118. #endif /* vax */
  1119.     offset += n_bits;
  1120.  
  1121.     return (code_int)code;
  1122. }
  1123.  
  1124. char *
  1125. rindex(s, c)        /* For those who don't have it in libc.a */
  1126. register char *s, c;
  1127. {
  1128.     char *p;
  1129.     for (p = NULL; *s; s++)
  1130.         if (*s == c)
  1131.         p = s;
  1132.     return(p);
  1133. }
  1134.  
  1135. #ifdef DEBUG
  1136. printcodes()
  1137. {
  1138.     /*
  1139.      * Just print out codes from input file.  For debugging.
  1140.      */
  1141.     code_int code;
  1142.     int col = 0, bits;
  1143.  
  1144.     bits = n_bits = INIT_BITS;
  1145.     maxcode = MAXCODE(n_bits);
  1146.     free_ent = ((block_compress) ? FIRST : 256 );
  1147.     while ( ( code = getcode() ) >= 0 ) {
  1148.     if ( (code == CLEAR) && block_compress ) {
  1149.            free_ent = FIRST - 1;
  1150.            clear_flg = 1;
  1151.     }
  1152.     else if ( free_ent < maxmaxcode )
  1153.         free_ent++;
  1154.     if ( bits != n_bits ) {
  1155.         fprintf(stderr, "\nChange to %d bits\n", n_bits );
  1156.         bits = n_bits;
  1157.         col = 0;
  1158.     }
  1159.     fprintf(stderr, "%5d%c", code, (col+=6) >= 74 ? (col = 0, '\n') : ' ' );
  1160.     }
  1161.     putc( '\n', stderr );
  1162.     exit( 0 );
  1163. }
  1164.  
  1165. code_int sorttab[1L<<BITS];    /* sorted pointers into htab */
  1166.  
  1167. dump_tab()    /* dump string table */
  1168. {
  1169.     register int i, first;
  1170.     register ent;
  1171. #define STACK_SIZE    15000
  1172.     int stack_top = STACK_SIZE;
  1173.     register c;
  1174.  
  1175.     if(do_decomp == 0) {    /* compressing */
  1176.     register int flag = 1;
  1177.  
  1178.     for(i=0; i<hsize; i++) {    /* build sort pointers */
  1179.         if((long)htabof(i) >= 0) {
  1180.             sorttab[codetabof(i)] = i;
  1181.         }
  1182.     }
  1183.     first = block_compress ? FIRST : 256;
  1184.     for(i = first; i < free_ent; i++) {
  1185.         fprintf(stderr, "%5d: \"", i);
  1186.         de_stack[--stack_top] = '\n';
  1187.         de_stack[--stack_top] = '"';
  1188.         stack_top = in_stack((htabof(sorttab[i])>>maxbits)&0xff, 
  1189.                                      stack_top);
  1190.         for(ent=htabof(sorttab[i]) & ((1L<<maxbits)-1);
  1191.             ent > 256;
  1192.             ent=htabof(sorttab[ent]) & ((1L<<maxbits)-1)) {
  1193.             stack_top = in_stack(htabof(sorttab[ent]) >> maxbits,
  1194.                         stack_top);
  1195.         }
  1196.         stack_top = in_stack(ent, stack_top);
  1197.         fwrite( &de_stack[stack_top], 1, STACK_SIZE-stack_top, stderr);
  1198.            stack_top = STACK_SIZE;
  1199.     }
  1200.    } else if(!debug) {    /* decompressing */
  1201.  
  1202.        for ( i = 0; i < free_ent; i++ ) {
  1203.        ent = i;
  1204.        c = tab_suffixof(ent);
  1205.        if ( isascii(c) && isprint(c) )
  1206.            fprintf( stderr, "%5d: %5d/'%c'  \"",
  1207.                ent, tab_prefixof(ent), c );
  1208.        else
  1209.            fprintf( stderr, "%5d: %5d/\\%03o \"",
  1210.                ent, tab_prefixof(ent), c );
  1211.        de_stack[--stack_top] = '\n';
  1212.        de_stack[--stack_top] = '"';
  1213.        for ( ; ent != 0;
  1214.            ent = (ent >= FIRST ? tab_prefixof(ent) : 0) ) {
  1215.            stack_top = in_stack(tab_suffixof(ent), stack_top);
  1216.        }
  1217.        fwrite( &de_stack[stack_top], 1, STACK_SIZE - stack_top, stderr );
  1218.        stack_top = STACK_SIZE;
  1219.        }
  1220.     }
  1221. }
  1222.  
  1223. int
  1224. in_stack(c, stack_top)
  1225.     register c, stack_top;
  1226. {
  1227.     if ( (isascii(c) && isprint(c) && c != '\\') || c == ' ' ) {
  1228.         de_stack[--stack_top] = c;
  1229.     } else {
  1230.         switch( c ) {
  1231.         case '\n': de_stack[--stack_top] = 'n'; break;
  1232.         case '\t': de_stack[--stack_top] = 't'; break;
  1233.         case '\b': de_stack[--stack_top] = 'b'; break;
  1234.         case '\f': de_stack[--stack_top] = 'f'; break;
  1235.         case '\r': de_stack[--stack_top] = 'r'; break;
  1236.         case '\\': de_stack[--stack_top] = '\\'; break;
  1237.         default:
  1238.          de_stack[--stack_top] = '0' + c % 8;
  1239.          de_stack[--stack_top] = '0' + (c / 8) % 8;
  1240.          de_stack[--stack_top] = '0' + c / 64;
  1241.          break;
  1242.         }
  1243.         de_stack[--stack_top] = '\\';
  1244.     }
  1245.     return stack_top;
  1246. }
  1247. #endif /* DEBUG */
  1248.  
  1249. writeerr()
  1250. {
  1251.     perror ( ofname );
  1252.     unlink ( ofname );
  1253.     exit ( 1 );
  1254. }
  1255.  
  1256. copystat(ifname, ofname)
  1257. char *ifname, *ofname;
  1258. {
  1259.     struct stat statbuf;
  1260.     int mode;
  1261.     time_t timep[2];
  1262.  
  1263.     fclose(stdout);
  1264.     if (stat(ifname, &statbuf)) {        /* Get stat on input file */
  1265.     perror(ifname);
  1266.     return;
  1267.     }
  1268.     if ((statbuf.st_mode & S_IFMT/*0170000*/) != S_IFREG/*0100000*/) {
  1269.     if(quiet)
  1270.             fprintf(stderr, "%s: ", ifname);
  1271.     fprintf(stderr, " -- not a regular file: unchanged");
  1272.     exit_stat = 1;
  1273.     } else if (statbuf.st_nlink > 1) {
  1274.     if(quiet)
  1275.             fprintf(stderr, "%s: ", ifname);
  1276.     fprintf(stderr, " -- has %d other links: unchanged",
  1277.         statbuf.st_nlink - 1);
  1278.     exit_stat = 1;
  1279.     } else if (exit_stat == 2 && (!force)) { /* No compression: remove file.Z */
  1280.     if(!quiet)
  1281.         fprintf(stderr, " -- file unchanged");
  1282.     } else {            /* ***** Successful Compression ***** */
  1283.     exit_stat = 0;
  1284.     mode = statbuf.st_mode & 07777;
  1285.     if (chmod(ofname, mode))        /* Copy modes */
  1286.         perror(ofname);
  1287. #ifndef DOS
  1288.     chown(ofname, statbuf.st_uid, statbuf.st_gid);    /* Copy ownership */
  1289. #endif
  1290.     timep[0] = statbuf.st_atime;
  1291.     timep[1] = statbuf.st_mtime;
  1292.     utime(ofname, timep);    /* Update last accessed and modified times */
  1293.     if (unlink(ifname))    /* Remove input file */
  1294.         perror(ifname);
  1295.     if(!quiet)
  1296.         fprintf(stderr, " -- replaced with %s", ofname);
  1297.     return;        /* Successful return */
  1298.     }
  1299.  
  1300.     /* Unsuccessful return -- one of the tests failed */
  1301.     if (unlink(ofname))
  1302.     perror(ofname);
  1303. }
  1304. /*
  1305.  * This routine returns 1 if we are running in the foreground and stderr
  1306.  * is a tty.
  1307.  */
  1308. foreground()
  1309. {
  1310.     if(bgnd_flag) {    /* background? */
  1311.         return(0);
  1312.     } else {            /* foreground */
  1313.         if(isatty(2)) {        /* and stderr is a tty */
  1314.             return(1);
  1315.         } else {
  1316.             return(0);
  1317.         }
  1318.     }
  1319. }
  1320.  
  1321. onintr ( )
  1322. {
  1323.     unlink ( ofname );
  1324.     exit ( 1 );
  1325. }
  1326. #ifndef DOS
  1327. oops ( )    /* wild pointer -- assume bad input */
  1328. {
  1329.     if ( do_decomp == 1 ) 
  1330.         fprintf ( stderr, "uncompress: corrupt input\n" );
  1331.     unlink ( ofname );
  1332.     exit ( 1 );
  1333. }
  1334. #endif
  1335. cl_block ()        /* table clear for block compress */
  1336. {
  1337.     register long int rat;
  1338.  
  1339.     checkpoint = in_count + CHECK_GAP;
  1340. #ifdef DEBUG
  1341.     if ( debug ) {
  1342.             fprintf ( stderr, "count: %ld, ratio: ", in_count );
  1343.              prratio ( stderr, in_count, bytes_out );
  1344.         fprintf ( stderr, "\n");
  1345.     }
  1346. #endif /* DEBUG */
  1347.  
  1348.     if(in_count > 0x007fffff) {    /* shift will overflow */
  1349.     rat = bytes_out >> 8;
  1350.     if(rat == 0) {        /* Don't divide by zero */
  1351.         rat = 0x7fffffff;
  1352.     } else {
  1353.         rat = in_count / rat;
  1354.     }
  1355.     } else {
  1356.     rat = (in_count << 8) / bytes_out;    /* 8 fractional bits */
  1357.     }
  1358.     if ( rat > ratio ) {
  1359.     ratio = rat;
  1360.     } else {
  1361.     ratio = 0;
  1362. #ifdef DEBUG
  1363.     if(verbose)
  1364.         dump_tab();    /* dump string table */
  1365. #endif
  1366.      cl_hash ( (count_int) hsize );
  1367.     free_ent = FIRST;
  1368.     clear_flg = 1;
  1369.     output ( (code_int) CLEAR );
  1370. #ifdef DEBUG
  1371.     if(debug)
  1372.             fprintf ( stderr, "clear\n" );
  1373. #endif /* DEBUG */
  1374.     }
  1375. }
  1376.  
  1377. cl_hash(hsize)        /* reset code table */
  1378.     register count_int hsize;
  1379. {
  1380.     register count_int huge *htab_p = htab+hsize;
  1381.     register long i;
  1382.     register long m1 = -1;
  1383.  
  1384.     i = hsize - 16;
  1385.      do {                /* might use Sys V memset(3) here */
  1386.         *(htab_p-16) = m1;
  1387.         *(htab_p-15) = m1;
  1388.         *(htab_p-14) = m1;
  1389.         *(htab_p-13) = m1;
  1390.         *(htab_p-12) = m1;
  1391.         *(htab_p-11) = m1;
  1392.         *(htab_p-10) = m1;
  1393.         *(htab_p-9) = m1;
  1394.         *(htab_p-8) = m1;
  1395.         *(htab_p-7) = m1;
  1396.         *(htab_p-6) = m1;
  1397.         *(htab_p-5) = m1;
  1398.         *(htab_p-4) = m1;
  1399.         *(htab_p-3) = m1;
  1400.         *(htab_p-2) = m1;
  1401.         *(htab_p-1) = m1;
  1402.         htab_p -= 16;
  1403.     } while ((i -= 16) >= 0);
  1404.         for ( i += 16; i > 0; i-- )
  1405.         *--htab_p = m1;
  1406. }
  1407.  
  1408. prratio(stream, num, den)
  1409. FILE *stream;
  1410.   long int num, den;    /* never want 16-bit */
  1411. {
  1412.     register int q;            /* Doesn't need to be long */
  1413.  
  1414.     if(num > 214748L) {        /* 2147483647/10000 */
  1415.         q = num / (den / 10000L);
  1416.     } else {
  1417.         q = 10000L * num / den;        /* Long calculations, though */
  1418.     }
  1419.     if (q < 0) {
  1420.         putc('-', stream);
  1421.         q = -q;
  1422.     }
  1423.     fprintf(stream, "%d.%02d%%", q / 100, q % 100);
  1424. }
  1425.  
  1426. version()
  1427. {
  1428.     fprintf(stderr, "%s\n", rcs_ident);
  1429.     fprintf(stderr, "Options: ");
  1430. #ifdef vax
  1431.     fprintf(stderr, "vax, ");
  1432. #endif
  1433. #ifdef NO_UCHAR
  1434.     fprintf(stderr, "NO_UCHAR, ");
  1435. #endif
  1436. #ifdef SIGNED_COMPARE_SLOW
  1437.     fprintf(stderr, "SIGNED_COMPARE_SLOW, ");
  1438. #endif
  1439. #ifdef COMPATIBLE
  1440.     fprintf(stderr, "COMPATIBLE, ");
  1441. #endif
  1442. #ifdef DEBUG
  1443.     fprintf(stderr, "DEBUG, ");
  1444. #endif
  1445. #ifdef BSD4_2
  1446.     fprintf(stderr, "BSD4_2, ");
  1447. #endif
  1448.     fprintf(stderr, "BITS = %d\n", BITS);
  1449. }
  1450.